import { defineConfig, searchForWorkspaceRoot, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import * as path from 'path'
import styleImport from 'vite-plugin-style-import'
import visualizer from 'rollup-plugin-visualizer'
import importToCDN, { autoComplete } from 'vite-plugin-cdn-import'

const { resolve } = path

export default ({ mode }) => {
  return defineConfig({
    base: '/xlmobile/',
    plugins: [
      vue(),
      styleImport({
        libs: [
          {
            libraryName: 'vant',
            esModule: true,
            //resolveStyle: (name) => `vant/es/${name}/style/less`,
          },
          {
            libraryName: 'vxe-table',
            esModule: true,
            resolveComponent: (name) => `vxe-table/es/${name}`,
            resolveStyle: (name) => `vxe-table/es/${name}/style.css`,
          },
        ],
      }),
      visualizer({
        // open: true,
        gzipSize: true,
        brotliSize: true,
      }),
      importToCDN({
        modules: [
          // autoComplete('vue'),
          // autoComplete('@vueuse/core'),
          autoComplete('axios'),
          // autoComplete('lodash'),
          // {
          //   name: 'vant',
          //   var: 'vant',
          //   path: `https://cdn.jsdelivr.net/npm/vant@3.2.5/lib/vant.min.js`,
          // },
          // {
          //   name: 'echarts',
          //   var: 'echarts',
          //   path: `https://cdn.jsdelivr.net/npm/echarts@5.2.1/dist/echarts.min.js`,
          // },
        ],
      }),
    ],
    server: {
      host: '0.0.0.0',
      port: 1200,
      fs: {
        allow: [searchForWorkspaceRoot(process.cwd())],
      },
      proxy: {
        '/api': {
          target: loadEnv(mode, process.cwd()).VITE_ROOT_PATH,
          changeOrigin: true,
          ws: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          // 覆盖样式变量
          // modifyVars: {
          //   'text-color': '#111',
          //   'border-color': '#eee',
          // },
        },
      },
    },
    resolve: {
      alias: [
        { find: /^~/, replacement: '' },
        { find: /^\/@/, replacement: resolve(__dirname, 'src') },
      ],
    },
    build: {
      //打包要注释此项
      sourcemap: true,
      rollupOptions: {
        // external: ['vue'],
        // plugins: [
        //   externalGlobals({
        //     vue: 'Vue',
        //   }),
        // ],
      },
    },
  })
}

// https://vitejs.dev/config/
